﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Text.RegularExpressions;
using QD.Utill;
using QD.Snapshot.Core.Config;
using NSoup.Nodes;
using NSoup.Select;
using System.Net;

namespace QD.Snapshot.Core.BLL
{
    public class Search_Sogou : SearchBase
    {
        static string SNUID = "";
        static string SUV = "";
        static int dbCount = 0;     //数据库查询次数
        static bool IsFristRun = true;

        public Search_Sogou(TextBox textBox, int SleepTime)
        {
            this.textBox = textBox;
            this.SleepTime = SleepTime;
            this.copyform = "2";        //搜狗搜索引擎
            Echo("搜狗移动截图已启动");
        }

        HttpRequest Http = new HttpRequest();
        string htmls, msg;
        Model.TaskModel_360 taskModel = new Model.TaskModel_360();
        public override void Search(string keyword, Model.Product product, Model.WebSite company)
        {
            Thread.Sleep(SleepTime);
            InitParam();
            Http.ClearCookie();
            Http.AddCookie("SNUID", SNUID, "sogou.com", DateTime.Now.AddYears(1));
            Http.AddCookie("SUV", SUV, "sogou.com", DateTime.Now.AddYears(1));
            //Http.UserAgent = "Mozilla/5.0 (Linux; Android 8.1; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36";
            Http.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36";
            Http.Referer = "https://m.sogou.com/";
            htmls = string.Empty;
        
            msg = Http.Requset(string.Format(Engine.URL_SOGOU, keyword), out htmls);
                
            IsCode_Sogou = CheckCode(htmls);   //是否出现验证码

            if (IsCode_Sogou)
            {
                EchoLog("code", "搜狗出现验证码");
                Thread.Sleep(1000);
            }
            else if (msg.Length > 1)
            {
                Echo(string.Format("搜索失败: {0}", msg));
            }
            else
            {
                Echo(string.Format("搜索 {0}", keyword));

            }
            taskModel.itemid = product.itemid;
            taskModel.keyword = keyword;
            taskModel.company = company;
            taskModel.html = htmls;

            NumHelper.Instance.SetNumSoGou(1);    //统计搜索速度
            ThreadPool.SetMinThreads(2, 1);
            ThreadPool.SetMaxThreads(5, 2);
            ThreadPool.QueueUserWorkItem(new WaitCallback(CheckOrAdd), taskModel);
        }

        void CheckOrAdd(object obj)
        {
            Model.TaskModel_360 model = obj as Model.TaskModel_360;
            model.html = Regex.Replace(model.html, "<!--([\\s\\S].*?)-->", "");

            CheckOrAdd(model.html, model.keyword, model.itemid, model.company);
        }

        void CheckOrAdd(string html, string keyword, int itemid, Model.WebSite company)
        {
            NSoup.Nodes.Document doc = NSoup.NSoupClient.Parse(html);
            Regex r1 = new Regex(FixRegex(company.ShortName), RegexOptions.IgnoreCase);
            Regex r2 = new Regex(FixRegex(keyword), RegexOptions.IgnoreCase);
            Regex SiteName = new Regex(FixRegex(company.SiteName), RegexOptions.IgnoreCase);
            Regex Cellphone = new Regex(FixRegex(company.Cellphone), RegexOptions.IgnoreCase);
            Regex phone = new Regex(FixRegex(company.Phone), RegexOptions.IgnoreCase);

            CheckOrAdd(doc, r1, SiteName, Cellphone, phone, itemid, company.UserID, keyword);
        }

        private object obj = new object();
        void CheckOrAdd(Document doc, Regex r1, Regex SiteName, Regex Cellphone, Regex phone, int itemid, int userid, string keyword, int page = 1)
        {
            Elements result = doc.GetElementsByClass("results");
            if (result == null || result.IsEmpty) return;
            Element parent = result[0];
            if (parent == null) return;

            HideElementList(doc.GetElementsByClass("recommend"));         //顶部广告
            HideElementList(doc.GetElementsByClass("vr-recommend"));    //推荐下载
            HideElementList(doc.GetElementsByClass("aside"));           //右边推荐
            HideElementList(doc.GetElementsByClass("per-hint"));        //还搜
            HideElementList(doc.GetElementsByClass("JS-extquery"));      //清空隐藏项
            HideElementList(doc.GetElementsByClass("ec_ad_results"));       //底部广告
            HideElementList(doc.GetElementsByClass("img-layout"));      //左边图片

            Elements list = parent.Select(".results > div"); //直接的下级DIV

            int index = 0;
            //bool isFirst = true;
            foreach (Element ele in list)
            {
                HideElement(doc.GetElementById("sogou_vr_11012201_" + index));     //清空 感兴趣
                HideElement(doc.GetElementById("formerhints"));     //其他人还搜
                HideElement(doc.GetElementById("sogou_vr_10000901_" + index));  //清空 搜狗购物
                HideElement(doc.GetElementById("sogou_vr_10000103_" + index)); //清空 搜狗图片
                HideElement(doc.GetElementById("kmap-right-container"));        //相关材料
                HideElement(doc.GetElementById("kmap-right-container02"));      //第二个
                HideElement(doc.GetElementById("sogou_vr_70104401_"+index+"_wrap"));
                //HideElement(doc.GetElementById("sogou_vr_70074601_aggrBox2_" + index)); //清空 搜狗影视 

                //if (ele.Attributes["class"] != "rb" && ele.Attributes["class"] != "vrwrap")
                //    continue;

                index++;
                if (r1.IsMatch(ele.Text()) || CheckShortNameList(ele.Text()) || CheckQJY(ele.Text(), SiteName, Cellphone, phone))
                {
                    string index_key = GetMd5(ele.GetElementsByTag("h3").Text); //第几行的key,更新时，用来确定更新哪一行
                    string platform = GetPlatform(ele.Html());    //上词的平台

                    //if (isFirst)
                    //{
                        RemoveAttr(result);
                    //    isFirst = false;
                    //}

                    //添加成功记录
                    lock (obj)
                    {
                        AddSnap(page, userid, itemid, index, keyword, result.Html(), platform, index_key);
                    }
                }
            }
        }

        protected override void RemoveAttr(Elements result)
        {
            Elements link = result.Select("link");
            link.Remove();

            Elements img = result.Select("img");
            img.Remove();

            Elements span = result.Select("span");
            span.RemoveAttr("onclick");

            Elements a = result.Select("a");
            a.RemoveAttr("href");
            a.RemoveAttr("bing_pb");

            Elements ec_ad_results = result.Select(".ec_ad_results");
            ec_ad_results.Remove();

            Elements img_layout = result.Select(".img-layout");
            img_layout.Remove();

            Elements script = result.Select("script");
            script.Remove();

            Elements style = result.Select("style");
            style.Remove();

            Elements i = result.Select("i");
            i.Remove();

            Elements vrtopic = result.Select(".vr-topic");
            vrtopic.Remove();

            if (Regex.IsMatch(result.Html(), "sogou_vr_11012201_([\\s\\S].*?)", RegexOptions.IgnoreCase))
            {
                MatchCollection mc = Regex.Matches(result.Html(), "sogou_vr_11012201_([\\s\\S].*?)", RegexOptions.IgnoreCase);
                for (int k = 0; k < mc.Count; k++) {
                    Elements vrresults = result.Select(mc[k].Groups[0].Value);
                    vrresults.Remove();
                }
            }
        }


        void InitParam()
        {
            if (!IsFristRun)//首次运行先获取一下
            {
                if (!IsCode_Sogou) return;    //未出现验证码
            }
            IsFristRun = false;//恢复运行

            //出现验证码，获取最新的 SNUID 和 SUV
            try
            {
                Dictionary<string, object> dic = BLL.SnapToken.GetBySogou(true);
                if (dic != null)
                {
                    SNUID = Convert.ToString(dic["SNUID"]);
                    SUV = Convert.ToString(dic["SUV"]);
                }
            }
            catch { }

            //记录次数
            dbCount++;
            if (dbCount >= 10)
            {
                Pigeon.Utility.Log.Write(string.Format("code{0}.log", DateTime.Now.ToString("yyyyMMdd")), string.Format("搜狗从数据库中拉取参数{0}次！", dbCount));
                dbCount = 0;
            }
        }
    }
}